/*
 * Copyright (c) 2001, Aslak Hellesøy, BEKK Consulting
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * - Redistributions of source code must retain the above copyright notice,
 *   this list of conditions and the following disclaimer.
 *
 * - Redistributions in binary form must reproduce the above copyright
 *   notice, this list of conditions and the following disclaimer in the
 *   documentation and/or other materials provided with the distribution.
 *
 * - Neither the name of BEKK Consulting nor the names of its
 *   contributors may be used to endorse or promote products derived from
 *   this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
 * DAMAGE.
 */
package middlegen.plugins.hibernate;

import java.util.Collection;
import java.util.Iterator;

import middlegen.Column;
import middlegen.RelationshipRole;
import middlegen.Table;
import middlegen.Util;
import middlegen.javax.JavaRelationshipRole;
import middlegen.predicates.column.PrimaryKey;
import middlegen.util.BooleanNode;

/**
 * The relationship role decorator used by the Hibernate plugin.
 *
 * @author <a href="mailto:ben@benlitchfield.com">Ben Litchfield</a>
 * @created July 16, 2005
 * @version 2.1
 */
public class HibernateRelationshipRole extends JavaRelationshipRole {

   /**
    * @todo-javadoc Describe the field
    */
   private String _cascade = null;

   /**
    * @todo-javadoc Describe the field
    */
   private String _collectionType = null;

   /**
    * @todo-javadoc Describe the field
    */
   private String _collectionIndex = null;

   /**
    * @todo-javadoc Describe the field
    */
   private BooleanNode _lazy = BooleanNode.createRoot(true);

   /**
    * Initialize the decorator with the given relationship role.
    *
    * @param subject The relationship role object to decorate.
    */
   public HibernateRelationshipRole(RelationshipRole subject) {
      super(subject);
   }

   /**
    * hibernate cascade option.
    *
    * @param cascade hibernate cascade.
    */
   public void setCascade(String cascade) {
      setPrefsValue("cascade", cascade);
      _cascade = cascade;
   }

   /**
    * Set the type of collection, ie set|list|map|...
    *
    * @param collectionType The type of collection.
    */
   public void setCollectionType(String collectionType) {
      setPrefsValue("collectionType", collectionType);
      _collectionType = collectionType;
   }

   /**
    * Set the collection index, only useful for lists and maps.
    *
    * @param collectionIndex The index of the collection.
    */
   public void setCollectionIndex(String collectionIndex) {
      setPrefsValue("collectionIndex", collectionIndex);
      _collectionIndex = collectionIndex;
   }

   /**
    * Set lazy attribute.
    *
    * @param lazy The lazy attribute.
    */
   public void setLazy(boolean lazy) {
      setPrefsValue("lazy", Util.string(lazy));
      _lazy.setValue(lazy);
   }

   /**
    * get the current cascade option.
    *
    * @return the current cascade option.
    */
   public String getCascade() {
      return _cascade;
   }

   /**
    * The type of collection.
    *
    * @return set|list|map|...
    */
   public String getCollectionType() {
      return _collectionType;
   }

   /**
    * A convenience method to determine if the VM file should write out the index attribute.
    *
    * @return The result of the flag.
    */
   public boolean isCollectionTypeUsesIndex() {
      String type = getCollectionTypeOrProjectDefault();
      return "map".equals(type) ||
            "list".equals(type);
   }

   /**
    * The index of collection.
    *
    * @return The column name to use for the index.
    */
   public String getCollectionIndex() {
      return _collectionIndex;
   }

   /**
    * Retrieve the cascade option from either the relationship or the project if it is specified
    *
    * @return
    */
   public String getRoleCascadeOrProjectDefault() {
      String retval = _cascade;
      if (retval == null) {
         retval = ((HibernatePlugin) getPlugin()).getStandardCascade();
      }
      return retval;
   }

   /**
    * Get the collection type that will actually be used. Retrieved from either the project or for this specific role.
    *
    * @return The collection type that will be actually used
    */
   public String getCollectionTypeOrProjectDefault() {
      String retval = _collectionType;
      if (retval == null) {
         retval = ((HibernatePlugin) getPlugin()).getStandardCollectionType();
      }
      return retval;
   }

   /**
    * Check lazy flag.
    *
    * @return The lazy value
    */
   public boolean isLazy() {
      return _lazy.isCompletelyTrue();
   }

   /**
    * Get the boolean node.
    *
    * @return The LazyNode value.
    */
   public BooleanNode getLazyNode() {
      return _lazy;
   }

   /**
    * @see JavaRelationshipRole#init()
    */
   protected void init() {
      super.init();
      setCascade(getPrefsValue("cascade"));
      if (getPrefsValue("lazy") != null) {
         setLazy(Util.bool(getPrefsValue("lazy")));
      }
      if (getPrefsValue("collectionType") != null) {
         setCollectionType(getPrefsValue("collectionType"));
      }
      if (getPrefsValue("collectionIndex") != null) {
         setCollectionIndex(getPrefsValue("collectionIndex"));
      }
      else {
         //lets try to automatically set the default to
         //be the pk of the table.
         Table targetTable = getTarget();
         Table originTable = getOrigin();
         Column targetPK = targetTable.getPkColumn();
         Column originPK = originTable.getPkColumn();
         if (targetPK != null) {
            //then the target table only has one PK
            //column and we can easily use that
            setCollectionIndex(targetPK.getSqlName());
         }
         else if (originPK != null) {
            //It is possible that we have a multiple column
            //relationship.  That is not supported right now, but
            //lets handle the special case where there are two keys
            //and one of them is back to the origin, for example
            // User(user_id) -> Granted_role(user_id,role_id)
            // We will assume that the map can just have the key
            // of role_id because we are traversing from the user

            Collection columns = targetTable.getColumns(PrimaryKey.getInstance());
            Column columnToUse = null;
            boolean valid = true;
            Iterator iter = columns.iterator();
            while (iter.hasNext()) {
               Column c = (Column) iter.next();
               if (!(c.getSqlName().equals(originPK.getSqlName()))) {
                  if (columnToUse != null) {
                     valid = false;
                  }
                  else {
                     columnToUse = c;
                  }
               }
               else {

               }
            }
            if (valid) {
               setCollectionIndex(columnToUse.getSqlName());
            }
         }
         else {
            //either no primary key or multiple primary keys
            //the user will need to specify the column to use
         }

      }
   }
}
